import React, { useState, useEffect, useCallback } from 'react';
import { Spin, Radio } from 'antd';
import { Pie } from '@ant-design/charts';
import { flatTryCatch } from '../../../servers/http';
import { homeAllCost } from 'admin/servers/servers';
import { timeOptions } from './constant';
import type { ITimeSpan } from './constant';

const nameMap = {
  hangduanCost: '行业短信',
  fenceCost: '靶向短信',
  intelligencecallCallCost: '智能外呼',
};

const SecondStatistic: React.FC = () => {
  const [timeSpan, setTimeSpan] = useState<ITimeSpan>(timeOptions[0].value);

  const [costData, setCostData] = useState<any>({
    data: [],
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    // 暖色系配色
    color: ['#ff7f0e', '#ffbb78', '#d62728'],
    // 标签配置
    label: {
      type: 'inner',
      offset: '-30%',
      content: '{percentage}',
      style: {
        fontSize: 14,
        textAlign: 'center',
      },
    },
    legend: { position: 'bottom' },
    // 提示框配置
    tooltip: {
      showTitle: true,
      fields: ['type', 'value', 'percentage'], // 明确指定要显示的字段
      formatter: datum => {
        return {
          name: datum.type,
          value: datum.value,
        };
      },
    },
    interactions: [{ type: 'element-active' }, { type: 'pie-legend-active' }],
  });
  const [loading, setLoading] = useState(false);

  // 处理数据
  const handleData = useCallback((allData: any) => {
    const statisticalData = Object.entries(allData)
      .map(([key, value]) => {
        if (nameMap[key]) {
          return {
            type: nameMap[key],
            value,
          };
        }
      })
      .filter(Boolean);

    setCostData(prev => ({
      ...prev,
      data: statisticalData,
    }));
  }, []);

  // 请求数据
  const fetchData = useCallback(async () => {
    setLoading(true);
    const { response, error } = await flatTryCatch(homeAllCost(timeSpan));
    setLoading(false);
    if (error) return;
    handleData(response.data);
  }, [handleData, timeSpan]);

  // 初始化加载和timeSpan变化时加载数据
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 处理时间范围变化
  const handleTimeSpanChange = (e: any) => {
    setTimeSpan(e.target.value);
  };

  return (
    <div className="single-item">
      <div className="single-title-wrapper">
        <div className="single-title">费用分布</div>
        <Radio.Group
          value={timeSpan}
          onChange={handleTimeSpanChange}
          buttonStyle="solid"
          optionType="button"
          options={timeOptions}
          size="small"
        />
      </div>
      <Spin spinning={loading}>
        <Pie {...costData} style={{ height: 400 }} />
      </Spin>
    </div>
  );
};

export default SecondStatistic;
